# -*- coding: utf-8 -*-
"""
心理咨询师服务系统 - 基础模型类
"""

from datetime import datetime
from app import db


class BaseModel(db.Model):
    """基础模型类，包含通用字段"""
    
    __abstract__ = True
    
    id = db.Column(db.Integer, primary_key=True, comment='主键ID')
    created_at = db.Column(
        db.DateTime, 
        nullable=False, 
        default=datetime.utcnow,
        comment='创建时间'
    )
    updated_at = db.Column(
        db.DateTime, 
        nullable=False, 
        default=datetime.utcnow, 
        onupdate=datetime.utcnow,
        comment='更新时间'
    )
    
    def to_dict(self, exclude=None, include_relationships=False):
        """转换为字典格式"""
        exclude = exclude or []
        result = {}
        
        # 获取所有列
        for column in self.__table__.columns:
            if column.name not in exclude:
                value = getattr(self, column.name)
                if isinstance(value, datetime):
                    value = value.isoformat()
                result[column.name] = value
        
        # 包含关系数据（可选）
        if include_relationships:
            for relationship in self.__mapper__.relationships:
                if relationship.key not in exclude:
                    value = getattr(self, relationship.key)
                    if value is not None:
                        if hasattr(value, '__iter__') and not isinstance(value, str):
                            # 一对多关系
                            result[relationship.key] = [item.to_dict() for item in value]
                        else:
                            # 一对一关系
                            result[relationship.key] = value.to_dict()
        
        return result
    
    def update_from_dict(self, data, exclude=None):
        """从字典更新模型"""
        exclude = exclude or ['id', 'created_at', 'updated_at']
        
        for key, value in data.items():
            if key not in exclude and hasattr(self, key):
                setattr(self, key, value)
    
    def save(self):
        """保存到数据库"""
        db.session.add(self)
        db.session.commit()
        return self
    
    def delete(self):
        """从数据库删除"""
        db.session.delete(self)
        db.session.commit()
    
    @classmethod
    def get_by_id(cls, id):
        """根据ID获取记录"""
        # 如果ID是字符串，尝试转换为整数
        if isinstance(id, str):
            try:
                id = int(id)
            except (ValueError, TypeError):
                return None
        return cls.query.get(id)
    
    @classmethod
    def get_or_404(cls, id):
        """根据ID获取记录，不存在则返回404"""
        return cls.query.get_or_404(id)
    
    @classmethod
    def create(cls, **kwargs):
        """创建新记录"""
        instance = cls(**kwargs)
        return instance.save()
    
    def __repr__(self):
        return f'<{self.__class__.__name__} {self.id}>'